// updated 2024/05/23
import zip from 'adm-zip'
import os from 'os'
import path from 'path'

export default function myCustomBuildPlugin(outPath) {
  return {
    name: 'build-plugin-package-dist',
    apply: 'build',
    closeBundle() {
      executeBuildScript(outPath)
    }
  }
}

function executeBuildScript(outPath) {
  const targetPath = resolveHome(outPath)
  const archive = new zip()
  archive.addLocalFolder('./dist', 'dist')
  archive.writeZip(targetPath)

  console.log('🏅 Package dist file compressed success at', new Date().toLocaleString(), ', output path:', outPath)
}

// 解析用户目录路径
function resolveHome(filepath) {
  if (filepath.startsWith('~')) {
    return path.join(os.homedir(), filepath.slice(1))
  }
  return filepath
}
